import Food from './food.js'
import Snake from './snake.js'
class Game {
  timer = null
  keyCode = 39
  constructor(map) {
    this.food = new Food()
    this.snake = new Snake()
    this.map = map
  }
  //游戏开始
  start() {
    this.food.render(this.map)
    this.snake.render(this.map)
    //开始游戏
    this.snakeRun()
    //通过上下左右控制蛇运动的方向
    this.directionDown()
  }
  snakeRun() {
    this.timer = setInterval(() => {
      this.snake.run(this.map)
      //蛇头的位置
      let headX = this.snake.body[0].x
      let headY = this.snake.body[0].y
      //判断蛇与边界是否有碰撞或者与自身碰撞
      let maxX = this.map.offsetWidth / this.snake.width
      let maxY = this.map.offsetHeight / this.snake.height
      //与边界碰撞
      if (headX < 0 || headX >= maxX || headY < 0 || headY >= maxY) {
        //超出边界游戏结束
        this.gameOver()
      }
      //与自己碰撞
      this.snake.body.forEach((v, i) => {
        if (i > 0 && v.x === headX && v.y === headY) {
          this.gameOver()
        }
      })
      //判断是否吃到食物如果吃到食物食物重新刷新位置，蛇长+1
      for (let v of this.food.sub) {
        if (
          v.offsetLeft === headX * this.snake.width &&
          v.offsetTop === headY * this.snake.height
        ) {
          //清除food 重新加载一个食物
          this.food.deleteSub(v, this.map)
          this.food.render(this.map)
          //增加蛇节
          let last = this.snake.body[this.snake.body.length - 1]
          this.snake.body.push(last)
        }
      }
    }, 150)
  }
  gameOver() {
    clearInterval(this.timer)
    alert('game over')
  }
  directionDown() {
    let _this = this
    document.onkeydown = function (e) {
      //如果当前方向与操作方向是反向或者同向则不处理
      if (
        _this.keyCode == e.keyCode ||
        Math.abs(_this.keyCode - e.keyCode) === 2
      ) {
        return
      }
      switch (e.keyCode) {
        case 37:
          _this.snake.direction = 'left'
          break
        case 38:
          _this.snake.direction = 'top'
          break
        case 39:
          _this.snake.direction = 'right'
          break
        case 40:
          _this.snake.direction = 'bottom'
          break
      }
      _this.keyCode = e.keyCode
    }
  }
}

export default Game
